package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.Notice;
import com.gaohe.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

@Slf4j
@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param title
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam("page") Integer page,
                  @RequestParam("pageSize") Integer pageSize,
                  @RequestParam(value = "name", required = false) String title) {
        Page<Notice> noticePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Notice> qw = new LambdaQueryWrapper<>();
        qw.like(ObjectUtils.isNotEmpty(title), Notice::getTitle, title);
        qw.orderByDesc(Notice::getUpdateTime);
        noticeService.page(noticePage, qw);
        return R.success(noticePage);
    }


    /**
     * 新增
     *
     * @param notice
     * @return
     */
    @PostMapping
    public R add(@RequestBody Notice notice) {
        notice.setCreateTime(LocalDate.now());
        notice.setUpdateTime(LocalDate.now());
        boolean save = noticeService.save(notice);
        return save ? R.success("新增成功") : R.error("新增失败");
    }

    /**
     * 根据 id 查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Long id) {
        return R.success(noticeService.getById(id));
    }

    /**
     * 修改
     *
     * @param notice
     * @return
     */
    @PutMapping
    public R updateById(@RequestBody Notice notice) {
        notice.setUpdateTime(LocalDate.now());
        return noticeService.updateById(notice) ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 根据 id 删除
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteById(@RequestParam Long id) {
        return noticeService.removeById(id) ? R.success("删除成功") : R.error("删除失败");
    }


    /**
     * 查询全部
     * @return
     */
    @GetMapping
    public R getAll(){
        return R.success(noticeService.list());
    }
}
